package org.flowable.app.cusTaskExe;

import cmbchina.util.AjaxJson;
import cmbchina.util.RunScript;
import cmbchina.util.common.CusTaskComonOptUtils;
import cmbchina.util.db.FlowDb;
import cmbchina.util.db.FlowFormDb;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.flowable.app.model.runtime.CompleteFormRepresentation;

import org.flowable.engine.HistoryService;
import org.flowable.engine.ProcessEngine;
import org.flowable.engine.ProcessEngines;
import org.flowable.engine.TaskService;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.flowable.task.service.delegate.DelegateTask;
import org.flowable.variable.api.persistence.entity.VariableInstance;
import org.slf4j.LoggerFactory;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by sevenlm on 2017/12/22.
 */
public class CusTaskOptParams {

    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(CusTaskOptParams.class);

    public Map<String,Object> optFormInfo(Map<String,Object> startFormMap, Map<String,Object> currentFormInfo, DelegateTask listener){

        Object value="";
        Map<String,Object> returnMap = new LinkedHashMap<>();
        for(String key:currentFormInfo.keySet()){

            //先从流程全局变量中获取变量
            Object obj = listener.getVariable(key);
            //如果获取不到
            if(obj==null){

                //如果获取不到再从开始节点获取
                value =  startFormMap.get(key);
                //如果还是获取不到，拿当前节点本来的值
                if(value==null){
                    //
                    if(currentFormInfo.get(key)==null){

                    }
                    else{
                        //当前节点存在未配置参数的表单字段，预留后续处理
                    }
                    value = currentFormInfo.get(key);
                }
            }else{
                value = obj;
            }
            returnMap.put(key,value);


        }
        return returnMap;
    }

    /**
     * 执行前处理表单参数（按照先去流程全局变量中取值，如果没有取到再在当前表单中取）
     * @param listener
     * @param taskDefinitionKey
     * @param processInstanceId
     * @return
     */
    public AjaxJson optCompleteFormRepresentation(DelegateTask listener, String taskDefinitionKey,String processInstanceId){
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.setSuccess(false);

        //查询当前节点配置的参数
        String currentFormInfo = FlowFormDb.queryFormInfo(taskDefinitionKey,processInstanceId);
        //开始节点的表单
        String startFormInfo = FlowFormDb.queryFormInfoByTaskType("StartEvent",processInstanceId);


        CompleteFormRepresentation completeTaskFormRepresentation = new CompleteFormRepresentation();
        if(null!=currentFormInfo &&!"".equals(currentFormInfo)){

            try{
                ObjectMapper obj = new ObjectMapper();
                Map<String,Object> map = obj.readValue(currentFormInfo,Map.class);
                Map<String,Object> formInfoMap = (Map<String, Object>) map.get("formInfo");

                completeTaskFormRepresentation.setFormId((String) formInfoMap.get("formId"));
                completeTaskFormRepresentation.setOutcome(formInfoMap.get("outcome")==null?null:formInfoMap.get("outcome").toString());

                formInfoMap = new CusTaskComonOptUtils().optFormInfo((Map<String, Object>)obj.readValue(startFormInfo,Map.class).get("formInfo"),(Map<String, Object>) map.get("formInfo"),listener);
                map.put("formInfo",formInfoMap);
                completeTaskFormRepresentation.setValues((Map<String, Object>) formInfoMap.get("values"));
//                CompleteFormRepresentation completeTaskFormRepresentation = obj.readValue(map.get("formInfo"),CompleteFormRepresentation.class);
                //更新一下form表单的值
                FlowFormDb.updateFormInfo(obj.writeValueAsString(map),taskDefinitionKey,processInstanceId);
                ajaxJson.setSuccess(true);
                ajaxJson.setObj(completeTaskFormRepresentation);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        else
        {
            //将流程状态置为待输入参数
            FlowDb.updateFlowState(7, listener.getProcessInstanceId());
        }
        return  ajaxJson;
    }

    public AjaxJson optRunTaskparams(HistoryService historyService, TaskService taskService, String processInstanceId){

        AjaxJson ajaxJson = new AjaxJson();

        List<HistoricTaskInstance> tasks = historyService.createHistoricTaskInstanceQuery().processInstanceId(processInstanceId).unfinished().list();

        if(!(tasks!=null&&tasks.size()>0)){

            ajaxJson.setSuccess(false);
            ajaxJson.setMsg("当前流程无未执行的节点！");
            return ajaxJson;
        }
        String taskId = tasks.get(0).getId();
        String taskDefinitionKey = tasks.get(0).getTaskDefinitionKey();

//        Map<String,Object> map1= taskService.createTaskQuery().processInstanceId(listener.getProcessInstanceId()).singleResult().getProcessVariables();
//        Map<String,Object> map2= taskService.createTaskQuery().processInstanceId(listener.getProcessInstanceId()).singleResult().getTaskLocalVariables();
//        Map<String,Object> map3= listener.getVariables();
        ajaxJson = new CusTaskOptParams().optCompleteFormRepresentationByTaskservice(taskService,taskDefinitionKey,taskId,processInstanceId);


        if(ajaxJson.isSuccess()){

            CompleteFormRepresentation completeTaskFormRepresentation = (CompleteFormRepresentation) ajaxJson.getObj();
            String task_type = FlowFormDb.queryTaskType(taskDefinitionKey,processInstanceId);
            if(StringUtils.isNotBlank(task_type)){
                if("cusScriptTask".equals(task_type)){
                    ajaxJson =new CusScriptTask().exe(completeTaskFormRepresentation, taskService, taskId, tasks.get(0).getDescription(),processInstanceId,taskDefinitionKey);
                }else if("cusSendSmsTask".equals(task_type)){
                    ajaxJson =new CusSendSmsTask().exe(completeTaskFormRepresentation, taskService, taskId, tasks.get(0).getDescription(),processInstanceId,taskDefinitionKey);
                }else if("cusCheckItilTask".equals(task_type)){
                    ajaxJson =new CusCheckItilTask().exe(completeTaskFormRepresentation, taskService, taskId, tasks.get(0).getDescription(),processInstanceId,taskDefinitionKey);
                }
                else if("CusSpecialScriptTask".equals(task_type)){
                    ajaxJson =new CusSpecialScriptTask().exe(completeTaskFormRepresentation, taskService, taskId, tasks.get(0).getDescription(),processInstanceId,taskDefinitionKey);
                }
            }

        }
        return ajaxJson;
    }

    public AjaxJson optCompleteFormRepresentationByTaskservice(TaskService taskService, String taskDefinitionKey,String taskid,String processInstanceId){
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.setSuccess(false);


        //查询当前节点配置的参数
        String currentFormInfo = FlowFormDb.queryFormInfo(taskDefinitionKey,processInstanceId);
        //开始节点的表单
        String startFormInfo = FlowFormDb.queryFormInfoByTaskType("StartEvent",processInstanceId);


        CompleteFormRepresentation completeTaskFormRepresentation = new CompleteFormRepresentation();
        if(null!=currentFormInfo &&!"".equals(currentFormInfo)){

            try{
                ObjectMapper obj = new ObjectMapper();
                Map<String,Object> map = obj.readValue(currentFormInfo,Map.class);
                Map<String,Object> formInfoMap = (Map<String, Object>) map.get("formInfo");

                completeTaskFormRepresentation.setFormId((String) formInfoMap.get("formId"));
                completeTaskFormRepresentation.setOutcome(formInfoMap.get("outcome")==null?null:formInfoMap.get("outcome").toString());
                formInfoMap = new CusTaskComonOptUtils().optFormInfoByService((Map<String, Object>)obj.readValue(startFormInfo,Map.class).get("formInfo"),(Map<String, Object>) map.get("formInfo"),taskService,taskid,processInstanceId);
                map.put("formInfo",formInfoMap);
                completeTaskFormRepresentation.setValues((Map<String, Object>) formInfoMap.get("values"));
//                CompleteFormRepresentation completeTaskFormRepresentation = obj.readValue(map.get("formInfo"),CompleteFormRepresentation.class);
                //更新一下form表单的值
                FlowFormDb.updateFormInfo(obj.writeValueAsString(map),taskDefinitionKey,processInstanceId);
                ajaxJson.setSuccess(true);
                ajaxJson.setObj(completeTaskFormRepresentation);
            }catch (Exception e){
                LOGGER.error("",e);
            }
        }
        else
        {
            //将流程状态置为待输入参数
            FlowDb.updateFlowState(7, processInstanceId);
        }
        return  ajaxJson;
    }
}
